<template>
	<div>
		<!-- <div class="mb-[10px] flex items-center gap-4">
            城市：
			<el-select
				v-model="cityId"
				placeholder="全部"
				style="max-width: 120px; min-width: 100px"
			>
				<el-option label="全部" value=""></el-option>
				<template v-for="item in cityList" :key="item.value">
					<el-option :label="item.label" :value="item.value" />
				</template>
			</el-select>
            门店：
			<el-select
				v-model="shopId"
				placeholder="全部"
				style="max-width: 120px; min-width: 100px"
			>
				<el-option label="全部" value=""></el-option>
				<template v-for="item in shopList" :key="item.value">
					<el-option :label="item.label" :value="item.value" />
				</template>
			</el-select>
		</div> -->
		<!-- 为表格添加垂直和水平滚动容器 -->
		<div style="overflow: auto; height: 70vh; width: 100%;">
			<el-table :data="tableData" border :span-method="objectSpanMethod" style="min-width: 1000px;">
			<el-table-column label="城市" prop="cityName"></el-table-column>
			<!-- 动态生成代理商层级列 -->
			<template v-for="level in maxAgentLevel" :key="level">
				<el-table-column :label="`${level}级代理商`" :prop="`agent${level}`">
					<template #default="{ row }">
						{{ row.agentNames && row.agentNames[level - 1] || '' }}
					</template>
				</el-table-column>
			</template>
			<el-table-column label="门店" prop="shopName"></el-table-column>
			<el-table-column label="订单数" prop="orderCount"></el-table-column>
			<el-table-column label="金额" prop="amount"></el-table-column>
			</el-table>
		</div>
	</div>
</template>

<script lang="ts" setup>
defineOptions({
	name: 'appointment-board'
});

import { useCool } from '/@/cool';
import { onMounted, ref, watch, computed } from 'vue';
import dayjs from 'dayjs';

const { service } = useCool();

// 定义数据类型接口
export interface ShopData {
	cityName: string;
	cityId?: number;
	shopName: string;
	shopId?: number;
	orderCount: number;
	amount: number;
	isTotal?: boolean;
	isCityTotal?: boolean;
	isAgentTotal?: boolean;
	// 存储各级代理商信息
	agentLevel?: number;
	// 代理商层级名称数组
	agentNames?: string[];
	// 代理商层级ID数组
	agentUserIds?: number[];
}

const tableData = ref<ShopData[]>([]);
const cityId = ref('');
const shopId = ref('');
const appointmentTime = ref([
	dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
	dayjs().format('YYYY-MM-DD')
]);
// 最大代理商层级
const maxAgentLevel = ref(0);

// 监听城市变化
watch(cityId, () => {
	getData();
});

// 监听门店变化
watch(shopId, () => {
	getData();
});

onMounted(async () => {
	getSelection();
	getData();
});

const cityList = ref([]);
const shopList = ref([]);

async function getSelection() {
	const res = await service.order.city.getCityList({});
	if (res) {
		cityList.value = Object.values(res);
	}
	const res2 = await service.order.shop.getSelectList({});
	if (res2) {
		shopList.value = Object.values(res2);
	}
}

// 递归处理代理商结构
function processAgentChildren(agent: any, cityId: number, cityName: string, agentNames: string[], agentIds: number[], level: number, processedData: ShopData[], totals: {
	cityTotalOrderCount: number;
	cityTotalAmount: number;
	cityShopCount: number;
	totalOrderCount: number;
	totalAmount: number;
	totalShopCount: number;
}) {
	const currentNames = [...agentNames];
	const currentIds = [...agentIds];
	
	// 只有非"未知代理商"才添加到层级中
	if (agent.agentName !== '未知代理商') {
		currentNames.push(agent.agentName);
		currentIds.push(agent.agentUserId);
	}

	// 处理当前代理商的门店
	if (agent.shopArr && Array.isArray(agent.shopArr)) {
		agent.shopArr.forEach((shop: any) => {
			processedData.push({
				cityId,
				cityName,
				shopId: shop.shopId,
				shopName: shop.shopName,
				orderCount: shop.orderCount || 0,
				amount: shop.amount || 0,
				isTotal: false,
				agentLevel: level,
				agentNames: [...currentNames],
				agentUserIds: [...currentIds]
			});

			// 更新统计数据
			totals.cityTotalOrderCount += shop.orderCount || 0;
			totals.cityTotalAmount += shop.amount || 0;
			totals.cityShopCount++;
			totals.totalOrderCount += shop.orderCount || 0;
			totals.totalAmount += shop.amount || 0;
			totals.totalShopCount++;
		});
	}

	// 递归处理子代理商
	if (agent.children && Array.isArray(agent.children)) {
		agent.children.forEach((childAgent: any) => {
			processAgentChildren(childAgent, cityId, cityName, currentNames, currentIds, level + 1, processedData, totals);
		});
	}
}

// 计算最大代理商层级
function calculateMaxAgentLevel(data: ShopData[]) {
	let maxLevel = 0;
	data.forEach(item => {
		if (item.agentNames && item.agentNames.length > maxLevel) {
			maxLevel = item.agentNames.length;
		}
	});
	return maxLevel;
}

// 获取数据
async function getData() {
	const params = {
		cityId: cityId.value,
		shopId: shopId.value,
		isAgent: true
	};

	// const res: Record<string, any> = await service.order.city.tongkangShopBoard(params)
	const res: Record<string, any> = await service.agent.agent.agentShopBoard(params);
	const processedData: ShopData[] = [];
	const cityMap = new Map<string, number>();
	let totalOrderCount = 0;
	let totalAmount = 0;
	let totalShopCount = 0;

	// 遍历所有城市数据
	if (Array.isArray(res)) {
		res.forEach((cityData: any) => {
			const cityName = cityData.cityName || '';
			const cityId = cityData.cityId;
			let cityTotalOrderCount = 0;
			let cityTotalAmount = 0;
			let cityShopCount = 0;

			// 遍历每个一级代理商
			if (cityData.agentArr && Array.isArray(cityData.agentArr)) {
				cityData.agentArr.forEach((agent: any) => {
					// 初始化统计对象
					const totals = {
						cityTotalOrderCount,
						cityTotalAmount,
						cityShopCount,
						totalOrderCount,
						totalAmount,
						totalShopCount
					};

					// 递归处理代理商层级结构
					processAgentChildren(agent, cityId, cityName, [], [], 0, processedData, totals);

					// 更新城市统计数据
					cityTotalOrderCount = totals.cityTotalOrderCount;
					cityTotalAmount = totals.cityTotalAmount;
					cityShopCount = totals.cityShopCount;
					totalOrderCount = totals.totalOrderCount;
					totalAmount = totals.totalAmount;
					totalShopCount = totals.totalShopCount;
				});
			}

			// 添加城市合计行
			if (cityShopCount > 0) {
				processedData.push({
					cityName: '城市合计',
					shopName: cityShopCount,
					orderCount: cityTotalOrderCount,
					amount: cityTotalAmount,
					isTotal: true,
					isCityTotal: true
				});

				// 记录城市对应的行数
				cityMap.set(cityName, cityShopCount);
			}
		});
	}

	// 添加总合计行
	processedData.push({
		cityName: '合计',
		shopName: totalShopCount,
		orderCount: totalOrderCount,
		amount: totalAmount,
		isTotal: true
	});

	tableData.value = processedData;
	// 计算最大代理商层级
	maxAgentLevel.value = calculateMaxAgentLevel(processedData);
	// 保存城市映射供合并单元格使用
	cityRowMap.value = cityMap;
}

// 存储城市对应的行数
const cityRowMap = ref(new Map<string, number>());

// 合并单元格方法
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
	// 处理城市列的合并
	if (columnIndex === 0) {
		// 如果是合计行，不合并
		if (row.isTotal) {
			return { rowspan: 1, colspan: 1 };
		}

		const cityName = row.cityName;

		// 检查当前行是否是城市的第一行
		let isFirstRow = true;
		for (let i = rowIndex - 1; i >= 0; i--) {
			if (
				tableData.value[i] &&
				tableData.value[i].cityName === cityName &&
				!tableData.value[i].isTotal
			) {
				isFirstRow = false;
				break;
			}
		}

		if (isFirstRow) {
			// 计算当前城市需要合并的行数
			let rowspan = 0;
			for (let i = rowIndex; i < tableData.value.length; i++) {
				const currRow = tableData.value[i];
				
				// 如果是城市合计行或总合计行，结束计数
				if (!currRow || currRow.isCityTotal || currRow.cityName === '合计') {
					break;
				}
				
				// 统计同一城市的行数
				if (currRow.cityName === cityName) {
					rowspan++;
				} else {
					// 遇到不同城市，结束计数
					break;
				}
			}
			
			return { rowspan, colspan: 1 };
		} else {
			// 非第一行的城市单元格不显示
			return { rowspan: 0, colspan: 0 };
		}
	}

	// 处理代理商层级列的合并
	if (columnIndex > 0 && columnIndex <= maxAgentLevel.value) {
		// 如果是合计行，不合并
		if (row.isTotal) {
			return { rowspan: 1, colspan: 1 };
		}

		const level = columnIndex; // 当前层级（从1开始）
		const agentName = row.agentNames?.[level - 1];
		const cityName = row.cityName;

		// 如果当前层级没有代理商名称，不合并
		if (!agentName) {
			return { rowspan: 1, colspan: 1 };
		}

		// 检查当前行是否是相同层级代理商的第一行
		let isFirstRow = true;
		for (let i = rowIndex - 1; i >= 0; i--) {
			const prevRow = tableData.value[i];
			// 跳过合计行和不同城市的行
			if (prevRow && (prevRow.isTotal || prevRow.cityName !== cityName)) continue;
			
			// 检查当前层级的代理商名称是否相同
			// 同时需要确保之前的所有层级名称也相同（确保是同一分支）
			let isSameBranch = true;
			for (let l = 1; l <= level; l++) {
				const prevAgentName = prevRow.agentNames?.[l - 1];
				const currAgentName = row.agentNames?.[l - 1];
				if (prevAgentName !== currAgentName) {
					isSameBranch = false;
					break;
				}
			}
			
			if (isSameBranch) {
				isFirstRow = false;
				break;
			}
		}

		if (isFirstRow) {
			// 计算相同层级代理商需要合并的行数
			let rowspan = 0;
			for (let i = rowIndex; i < tableData.value.length; i++) {
				const currRow = tableData.value[i];
				// 跳过合计行和不同城市的行
				if (currRow && (currRow.isTotal || currRow.cityName !== cityName)) continue;
				
				// 检查是否是同一分支
				let isSameBranch = true;
				for (let l = 1; l <= level; l++) {
					const prevAgentName = row.agentNames?.[l - 1];
					const currAgentName = currRow.agentNames?.[l - 1];
					if (prevAgentName !== currAgentName) {
						isSameBranch = false;
						break;
					}
				}
				
				if (isSameBranch) {
					rowspan++;
				} else {
					break;
				}
			}
			return { rowspan, colspan: 1 };
		} else {
			// 非第一行的代理商单元格不显示
			return { rowspan: 0, colspan: 0 };
		}
	}

	// 处理其他列
	return { rowspan: 1, colspan: 1 };
}
</script>
